package com.learning.spring.aop.base.cglib;

import com.learning.spring.aop.base.AopMonitor;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * ClassName: CglibHandler
 * Description: Spring AOP 原理：CGLab 实现的 AOP 切入
 * Date: 2019/4/21 15:59 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class CglibHandler implements MethodInterceptor {

    /**
     * 获取代理
     *
     * @param clazz
     * @return
     */
    public Object getProxy(Class clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    /**
     * 拦截父类所有方法
     *
     * @param o           目标类实例
     * @param method      目标类方法的反射对象
     * @param objects     参数
     * @param methodProxy 代理实例
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        AopMonitor.start();

        // 操作新增的业务
        Object invoke = methodProxy.invokeSuper(o, objects);

        AopMonitor.end();

        return invoke;

    }
}
